<template>
  <d2-container>
    <el-dialog :visible.sync="dialogVisible4Preview">
      <img width="100%" :src="dialogImageUrl" alt>
    </el-dialog>

    <el-dialog
      ref="abc"
      title="编辑"
      :visible.sync="dialogVisible"
      width="1300px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-form ref="formContent" :rules="rules" :model="formContent" label-width="100px">
        <el-form-item label="分类">
          <el-select v-model="formContent.catalogCode">
            <el-option
              v-for="item in cataLogList"
              :label="item.name"
              :key="item.code"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预览图">
          <el-upload
            action="https://xcx.ruiysoft.com/reserve/qiniu/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :file-list="fileList"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="显示顺序">
          <el-input v-model="formContent.sequence"></el-input>
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="formContent.title"></el-input>
        </el-form-item>
        <el-form-item label="简介">
          <!-- <d2-ueditor v-model="text" style="font-size:20px;line-height:1;z-index:-1;"/> -->
          <el-input type="textarea" v-model="formContent.summary"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="formContent.phone"></el-input>
        </el-form-item>
        <el-form-item label="备注/地址">
          <el-input type="textarea" v-model="formContent.remarks"></el-input>
        </el-form-item>
        
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="submitForm('formContent')" size="small">确 定</el-button>
      </span>
    </el-dialog>

    <!-- <template slot="header">内容管理</template> -->
    <el-button type="primary" size="small" @click="createNew">新建</el-button>
    <el-button type="primary" size="small" @click="refresh">刷新</el-button>
    <el-divider></el-divider>
    <el-table :data="tableData" :stripe="true" :highlight-current-row="true">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="序号" type="index"></el-table-column>
      <el-table-column label="分类" width="180">
        <template slot-scope="scope">{{ scope.row.cataLogName }}</template>
      </el-table-column>
      <el-table-column label="预览图" width="180">
        <template slot-scope="scope">
          <img :src="scope.row.previewImage" width="50%">
        </template>
      </el-table-column>
      <el-table-column label="标题" width="300">
        <template slot-scope="scope">{{ scope.row.title }}</template>
      </el-table-column>
      <el-table-column label="显示顺序" width="180">
        <template slot-scope="scope">{{ scope.row.sequence }}</template>
      </el-table-column>
      <el-table-column label="电话" width="180">
        <template slot-scope="scope">{{ scope.row.phone }}</template>
      </el-table-column>
      <el-table-column label="创建时间" width="180">
        <template slot-scope="scope">{{ scope.row.createTime | dateFormat }}</template>
      </el-table-column>
      <el-table-column label="更新时间" width="180">
        <template slot-scope="scope">{{ scope.row.updateTime | dateFormat }}</template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="success" size="mini" @click="handleDetail(scope.$index, scope.row)">详情</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background layout="prev, pager, next" :total="25"></el-pagination>
  </d2-container>
</template>

<script>
import { getContentList, saveOrEdit, deleteById } from "@api/cms.content";
import { getCatalogList } from "@api/cms.catalog";
import { Message, MessageBox } from "element-ui";
import util from "@/libs/util.js";

/**
 * 日期格式化
 */
export function dateFormat(date) {
  let format = "yyyy-MM-dd hh:mm:ss";
  if (date !== "Invalid Date") {
    var o = {
      "M+": date.getMonth() + 1, // month
      "d+": date.getDate(), // day
      "h+": date.getHours(), // hour
      "m+": date.getMinutes(), // minute
      "s+": date.getSeconds(), // second
      "q+": Math.floor((date.getMonth() + 3) / 3), // quarter
      S: date.getMilliseconds() // millisecond
    };
    if (/(y+)/.test(format)) {
      format = format.replace(
        RegExp.$1,
        (date.getFullYear() + "").substr(4 - RegExp.$1.length)
      );
    }
    for (var k in o) {
      if (new RegExp("(" + k + ")").test(format)) {
        format = format.replace(
          RegExp.$1,
          RegExp.$1.length === 1
            ? o[k]
            : ("00" + o[k]).substr(("" + o[k]).length)
        );
      }
    }
    return format;
  }
  return "";
}

export default {
  data() {
    return {
      fileList: null,
      text: "",
      dialogImageUrl: "",
      dialogVisible4Preview: false,
      // 表单
      formContent: {
        catalogCode: "",
        title: "",
        phone: "",
        summary: "",
        remarks: "",
        sequence: ""
      },
      // 校验
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
      },
      dialogVisible: false,
      tableData: [],
      cataLogList: [],
      downloadPath: null
    };
  },
  filters: {
    dateFormat(time) {
      let date = new Date(time);
      return dateFormat(date, "yyyy-MM-dd hh:mm:ss");
    }
  },
  created: function() {
    getContentList({enterpriseId: util.cookies.get("enterpriseId"), catalogCode: null}) 
      .then(res => {
        console.log(res);
        this.tableData = res;
      })
      .catch(err => {
        console.log("err: ", err);
      });

    getCatalogList({enterpriseId: util.cookies.get("enterpriseId"), parentCode: null})
      .then(res => {
        console.log(res);
        this.cataLogList = res.data;
      })
      .catch(err => {
        console.log("err: ", err);
      });
  },
  methods: {
    createNew() {
      this.dialogVisible = true;
      this.$refs[formContent].resetFields();
      this.fileList = null;
    },

    refresh() {
      getContentList({enterpriseId: util.cookies.get("enterpriseId"), catalogCode: null})
        .then(res => {
          console.log(res);
          this.tableData = res;
        })
        .catch(err => {
          console.log("err: ", err);
        });
    },

    handleDetail(index, row) {
      this.$router.push({ path: "./detail", query:{
          id: row.id
        }});
    },

    handleEdit(index, row) {
      console.log(index, row);
      this.dialogVisible = true;

      // this.$refs.abc.title = "编辑";

      this.formContent.id = row.id;
      this.formContent.catalogCode = row.catalogCode;

      this.fileList = [{url: row.previewImage}];

      this.formContent.title = row.title;
      this.formContent.summary = row.summary;
      this.formContent.phone = row.phone;
      this.formContent.remarks = row.remarks;
      this.formContent.sequence = row.sequence;
      
    },
    handleDelete(index, row) {
      console.log(index, row);

      MessageBox.confirm("确认删除么？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteById(row.id)
            .then(res => {
              console.log(res);
              if (res.success) {
                Message({
                  type: "success",
                  duration: 1500,
                  message: "操作成功"
                });

                getContentList({enterpriseId: util.cookies.get("enterpriseId"), catalogCode: null})
                  .then(res => {
                    console.log(res);
                    this.tableData = res;
                  })
                  .catch(err => {
                    console.log("err: ", err);
                  });
              }
            })
            .catch(err => {
              console.log("err: ", err);
            });
        })
        .catch(() => {});
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(response, file, fileList) {
      console.log(response, file, fileList);
      this.downloadPath = response.downloadPath;
    },
    submitForm(form) {
      this.$refs.formContent.validate(valid => {
        if (valid) {
          console.log(this.formContent);

          this.formContent.enterpriseId = util.cookies.get("enterpriseId");
          this.formContent.previewImage = this.downloadPath;

          saveOrEdit(this.formContent)
            .then(res => {
              console.log(res);
              Message({
                type: "success",
                duration: 1500,
                message: "操作成功"
              });

              getContentList({enterpriseId: util.cookies.get("enterpriseId"), catalogCode: null})
                .then(res => {
                  console.log(res);
                  this.tableData = res;
                })
                .catch(err => {
                  console.log("err: ", err);
                });
            })
            .catch(err => {
              console.log("err: ", err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  }
};
</script>
